package com.zjw.nanyinge.feign.config.decoder;

import com.alibaba.fastjson.JSONObject;
import com.zjw.nanyinge.vo.resp.FileUploadRespVO;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.springframework.util.StringUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

public class WeChatFileDecoder implements Decoder {
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        Response.Body body = response.body();
        BufferedInputStream bis = new BufferedInputStream(body.asInputStream());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = bis.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
        String json = baos.toString(StandardCharsets.UTF_8);
        FileUploadRespVO fileUploadRespVO = JSONObject.parseObject(json, FileUploadRespVO.class);
        if (!StringUtils.hasLength(fileUploadRespVO.getMedia_id())) {
            throw new DecodeException(response.status(), "微信素材上传失败！" + fileUploadRespVO.getErrmsg(), response.request());
        }
        return fileUploadRespVO;
    }
}
